<?php
/***
 * Candy框架 数组操作类	
 * 
 * $Author: 刘森 (fingerboy@qq.com) $
 * $Date: 2020-02-03 20:08:03 $   
 */
 
declare(strict_types=1);
namespace Candy\Extend;
use ArrayAccess;

defined('CANDY') OR die('You Are A Bad Guy. o_O???');

final Class Arr
{

    /**
     * 确定给定值是否可以访问数组
     *
     * @param mixed $value
     * @return bool
     */
    public static function accessible($value): bool
    {
        return is_array($value) || $value instanceof ArrayAccess;
    }

    /**
     * 给不存在的键位添加值
     *
     * @param array  $array
     * @param string $key
     * @param mixed  $value
     * @return array
     */
    public static function add(array $array,string $key,mixed $value): array
    {
        if (is_null(self::get($array, $key))) {
            self::set($array, $key, $value);
        }

        return $array;
    }

    /**
     * 多维数组变一维数组
     *
     * @param array $array
     * @return array
     */
    public static function collapse(array $array): array
    {
        $results = [];

        foreach ($array as $values) {
            if ($values instanceof Collection) {
                $values = $values->all();
            } elseif (!is_array($values)) {
                continue;
            }

            $results = array_merge($results, $values);
        }

        return $results;
    }

    /**
     * Cross join the given arrays, returning all possible permutations.
     *
     * @param array ...$arrays
     * @return array
     */
    public static function crossJoin(array ...$arrays): array
    {
        $results = [[]];

        foreach ($arrays as $index => $array) {
            $append = [];

            foreach ($results as $product) {
                foreach ($array as $item) {
                    $product[$index] = $item;

                    $append[] = $product;
                }
            }

            $results = $append;
        }

        return $results;
    }

    /**
     * 分开数组的键值对
     *
     * @param array $array
     * @return array
     */
    public static function divide(array $array): array
    {
        return [array_keys($array), array_values($array)];
    }

    /**
     * Flatten a multi-dimensional associative array with dots.
     *
     * @param array  $array
     * @param string $prepend
     * @return array
     */
    public static function dot(array $array,string $prepend = ''): array
    {
        $results = [];

        foreach ($array as $key => $value) {
            if (is_array($value) && !empty($value)) {
                $results = array_merge($results, self::dot($value, $prepend . $key . '.'));
            } else {
                $results[$prepend . $key] = $value;
            }
        }

        return $results;
    }

    /**
     * Get all of the given array except for a specified array of keys.
     *
     * @param array        $array
     * @param array|string $keys
     * @return array
     */
    public static function except(string $array,array|string $keys): string
    {
        self::forget($array, $keys);

        return $array;
    }

    /**
     * Determine if the given key exists in the provided array.
     *
     * @param \ArrayAccess|array $array
     * @param string|int         $key
     * @return bool
     */
    public static function exists(ArrayAccess|array $array,string|int $key): bool
    {
        if ($array instanceof ArrayAccess) {
            return $array->offsetExists($key);
        }

        return array_key_exists($key, $array);
    }

    /**
     * Return the first element in an array passing a given truth test.
     *
     * @param array         $array
     * @param callable|null $callback
     * @param mixed         $default
     * @return mixed
     */
    public static function first(array $array, callable $callback = null,mixed $default = null): mixed
    {
        if (is_null($callback)) {
            if (empty($array)) {
                return value($default);
            }

            foreach ($array as $item) {
                return $item;
            }
        }

        foreach ($array as $key => $value) {
            if (call_user_func($callback, $value, $key)) {
                return $value;
            }
        }

        return value($default);
    }

    /**
     * Return the last element in an array passing a given truth test.
     *
     * @param array         $array
     * @param callable|null $callback
     * @param mixed         $default
     * @return mixed
     */
    public static function last(array $array, callable $callback = null,mixed $default = null): mixed
    {
        if (is_null($callback)) {
            return empty($array) ? value($default) : end($array);
        }

        return self::first(array_reverse($array, true), $callback, $default);
    }

    /**
     * Flatten a multi-dimensional array into a single level.
     *
     * @param array $array
     * @param int   $depth
     * @return array
     */
    public static function flatten(array $array,int $depth = INF): array
    {
        $result = [];

        foreach ($array as $item) {
            $item = $item instanceof Collection ? $item->all() : $item;

            if (!is_array($item)) {
                $result[] = $item;
            } elseif ($depth === 1) {
                $result = array_merge($result, array_values($item));
            } else {
                $result = array_merge($result, self::flatten($item, $depth - 1));
            }
        }

        return $result;
    }

    /**
     * Remove one or many array items from a given array using "dot" notation.
     *
     * @param array        $array
     * @param array|string $keys
     * @return void
     */
    public static function forget(array &$array,array|string $keys): void
    {
        $original = &$array;

        $keys = (array) $keys;

        if (count($keys) === 0) {
            return;
        }

        foreach ($keys as $key) {
            // if the exact key exists in the top-level, remove it
            if (self::exists($array, $key)) {
                unset($array[$key]);

                continue;
            }

            $parts = explode('.', $key);

            // clean up before each pass
            $array = &$original;

            while (count($parts) > 1) {
                $part = array_shift($parts);

                if (isset($array[$part]) && is_array($array[$part])) {
                    $array = &$array[$part];
                } else {
                    continue 2;
                }
            }

            unset($array[array_shift($parts)]);
        }
    }

    /**
     * Get an item from an array using "dot" notation.
     *
     * @param \ArrayAccess|array $array
     * @param string             $key
     * @param mixed              $default
     * @return mixed
     */
    public static function get(ArrayAccess|array $array,string $key,mixed $default = null): mixed
    {
        if (!self::accessible($array)) {
            return value($default);
        }

        if (is_null($key)) {
            return $array;
        }

        if (self::exists($array, $key)) {
            return $array[$key];
        }

        if (strpos($key, '.') === false) {
            return $array[$key] ?? value($default);
        }

        foreach (explode('.', $key) as $segment) {
            if (self::accessible($array) && self::exists($array, $segment)) {
                $array = $array[$segment];
            } else {
                return value($default);
            }
        }

        return $array;
    }

    /**
     * Check if an item or items exist in an array using "dot" notation.
     *
     * @param \ArrayAccess|array $array
     * @param string|array       $keys
     * @return bool
     */
    public static function has(ArrayAccess|array $array,string|array $keys): bool
    {
        $keys = (array) $keys;

        if (!$array || $keys === []) {
            return false;
        }

        foreach ($keys as $key) {
            $subKeyArray = $array;

            if (self::exists($array, $key)) {
                continue;
            }

            foreach (explode('.', $key) as $segment) {
                if (self::accessible($subKeyArray) && self::exists($subKeyArray, $segment)) {
                    $subKeyArray = $subKeyArray[$segment];
                } else {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Determines if an array is associative.
     *
     * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
     *
     * @param array $array
     * @return bool
     */
    public static function isAssoc(array $array): bool
    {
        $keys = array_keys($array);

        return array_keys($keys) !== $keys;
    }

    /**
     * Get a subset of the items from the given array.
     *
     * @param array        $array
     * @param array|string $keys
     * @return array
     */
    public static function only(array $array,array|string $keys): array
    {
        return array_intersect_key($array, array_flip((array) $keys));
    }

    /**
     * Pluck an array of values from an array.
     *
     * @param array             $array
     * @param string|array      $value
     * @param string|array|null $key
     * @return array
     */
    public static function pluck(array $array,string|array $value,string|array|null $key = null): array
    {
        $results = [];

        [$value, $key] = self::explodePluckParameters($value, $key);

        foreach ($array as $item) {
            $itemValue = data_get($item, $value);

            // If the key is "null", we will just append the value to the array and keep
            // looping. Otherwise we will key the array using the value of the key we
            // received from the developer. Then we'll return the final array form.
            if (is_null($key)) {
                $results[] = $itemValue;
            } else {
                $itemKey = data_get($item, $key);

                if (is_object($itemKey) && method_exists($itemKey, '__toString')) {
                    $itemKey = (string) $itemKey;
                }

                $results[$itemKey] = $itemValue;
            }
        }

        return $results;
    }

    /**
     * Explode the "value" and "key" arguments passed to "pluck".
     *
     * @param string|array      $value
     * @param string|array|null $key
     * @return array
     */
    protected static function explodePluckParameters(string|array $value,string|array|null $key): array
    {
        $value = is_string($value) ? explode('.', $value) : $value;

        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);

        return [$value, $key];
    }

    /**
     * Push an item onto the beginning of an array.
     *
     * @param array $array
     * @param mixed $value
     * @param mixed $key
     * @return array
     */
    public static function prepend(array $array,mixed $value,mixed $key = null): array
    {
        if (is_null($key)) {
            array_unshift($array, $value);
        } else {
            $array = [$key => $value] + $array;
        }

        return $array;
    }

    /**
     * Get a value from the array, and remove it.
     *
     * @param array  $array
     * @param string $key
     * @param mixed  $default
     * @return mixed
     */
    public static function pull(array &$array,string $key,mixed $default = null): mixed
    {
        $value = self::get($array, $key, $default);

        self::forget($array, $key);

        return $value;
    }

    /**
     * Get one or a specified number of random values from an array.
     *
     * @param array    $array
     * @param int|null $number
     * @return mixed
     *
     * @throws \Exception
     */
    public static function random(array $array,int|null $number = null): mixed
    {
        $requested = is_null($number) ? 1 : $number;

        $count = count($array);

        if ($requested > $count) {
            throw new \Exception(
                "You requested {$requested} items, but there are only {$count} items available."
            );
        }

        if (is_null($number)) {
            return $array[array_rand($array)];
        }

        if ((int) $number === 0) {
            return [];
        }

        $keys = array_rand($array, $number);

        $results = [];

        foreach ((array) $keys as $key) {
            $results[] = $array[$key];
        }

        return $results;
    }

    /**
     * Set an array item to a given value using "dot" notation.
     *
     * If no key is given to the method, the entire array will be replaced.
     *
     * @param array  $array
     * @param string $key
     * @param mixed  $value
     * @return array
     */
    public static function set(array &$array,string $key,mixed $value): array
    {
        if (is_null($key)) {
            return $array = $value;
        }

        $keys = explode('.', $key);

        while (count($keys) > 1) {
            $key = array_shift($keys);

            // If the key doesn't exist at this depth, we will just create an empty array
            // to hold the next value, allowing us to create the arrays to hold final
            // values at the correct depth. Then we'll keep digging into the array.
            if (!isset($array[$key]) || !is_array($array[$key])) {
                $array[$key] = [];
            }

            $array = &$array[$key];
        }

        $array[array_shift($keys)] = $value;

        return $array;
    }

    /**
     * Shuffle the given array and return the result.
     *
     * @param array    $array
     * @param int|null $seed
     * @return array
     */
    public static function shuffle(array $array,int|null $seed = null): array
    {
        if (is_null($seed)) {
            shuffle($array);
        } else {
            srand($seed);

            usort($array, function () {
                return rand(-1, 1);
            });
        }

        return $array;
    }

    /**
     * Sort the array using the given callback or "dot" notation.
     *
     * @param array                $array
     * @param callable|string|null $callback
     * @return array
     */
    public static function sort(array $array,callable|string|null $callback = null): array
    {
        return Collection::make($array)->sort($callback)->all();
    }

    /**
     * Recursively sort an array by keys and values.
     *
     * @param array $array
     * @return array
     */
    public static function sortRecursive(array $array): array
    {
        foreach ($array as &$value) {
            if (is_array($value)) {
                $value = self::sortRecursive($value);
            }
        }

        if (self::isAssoc($array)) {
            ksort($array);
        } else {
            sort($array);
        }

        return $array;
    }

    /**
     * Convert the array into a query string.
     *
     * @param array $array
     * @return string
     */
    public static function query(array $array): string
    {
        return http_build_query($array, null, '&', PHP_QUERY_RFC3986);
    }

    /**
     * Filter the array using the given callback.
     *
     * @param array    $array
     * @param callable $callback
     * @return array
     */
    public static function where(array $array, callable $callback): array
    {
        return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
    }

    /**
     * If the given value is not an array and not null, wrap it in one.
     *
     * @param mixed $value
     * @return array
     */
    public static function wrap(array $value): array
    {
        if (is_null($value)) {
            return [];
        }

        return is_array($value) ? $value : [$value];
    }
	
	/**
	 * 取出数组中第n项
	 *
	 * @param array $arr 数组数据
	 * @param int $index 取值位置
	 */
	public static function arrayGetIndex(array $arr,int $index): array
	{
	   foreach($arr as $k=>$v){
		   $index--;
		   if($index<0) return [$k, $v];
	   }
	   return [];
	}
	
	/**
	 * 过滤数组
	 *
	 * @param $filter 过滤的变量
	 * @param mixed $data 待过滤的数组
	 * @return mixed
	 */
	public static function arrayMapRecursive(string $filter,array $data): array
	{
		$result = [];
		foreach($data as $key => $val){
			$result[$key] = is_array($val) ? arrayMapRecursive($filter, $val) : call_user_func($filter, $val);
		}
		return $result;
	}
	
	/**
	 * 冒泡排序
	 * 
	 * @param  $array 
	 * @return array 
	 */
	public static function arrayBubbleSort(array $array): array
	{
		$count = count($array);
		if ($count<=0){
			return false;
		}
		for ($i=0; $i <$count ; $i++){ 
			for ($j=0; $j <$count-$i-1 ; $j++){ 
				if ($array[$j]>$array[$j+1]){
					$tmp = $array[$j+1];
					$array[$j+1]=$array[$j];
					$array[$j]=$tmp;
				}
			}
		}
		return $array;
	}
	
	/**
	 * 二维数组按照指定的键值进行排序，
	 * 
	 * @param  $records 二维数组
	 * @param  $field 根据键值
	 * @param  $reverse 升序降序
	 * @return array 
	 */
	public static function arraySort(array $records, string $field,bool $reverse=false): array
	{
		$hash = [];
		foreach($records as $addon=>$record){
			$key = $record[$field];
			while(isset($hash[$key])){
				$key++;
			}
			$hash[$key] = $addon;
		}
		
		$recordLists = [];
		foreach($hash as $record){
			$recordLists[$record]= $records[$record];
		}
		return $recordLists;
	}
	
	/**
	 * 遍历数组，对每个元素调用 $callback，假如返回值不为假值，则直接返回该返回值；
	 * 假如每次 $callback 都返回假值，最终返回 false
	 * 
	 * @param  $array 
	 * @param  $callback 
	 * @return mixed 
	 */
	public static function arrayTry(array $array, $callback, ...$args): mixed
	{
		if (!$array || !$callback){
			return false;
		}
		if (!$args){
			$args = [];
		} 
		foreach($array as $v){
			$params = $args;
			array_unshift($params, $v);
			$x = call_user_func_array($callback, $params);
			if ($x){
				return $x;
			} 
		} 
		return false;
	}
	
	/**
	 * 求多个数组的并集(值相同会覆盖)
	 */
	public static function arrayUnion(array ...$argsCount): array
	{
		$count = count($argsCount);
		if ($count < 2){
			return false;
		} else if (2 === $count){
			list($arr1, $arr2) = func_get_args();
			while ((list($k, $v) = each($arr2))){
				if (!in_array($v, $arr1)) $arr1[] = $v;
			} 
			return $arr1;
		} else { // 三个以上的数组合并
			$i = 0;
			$arr2 = $argsCount[0];
			do{
				$i++;
				$arr2 = self::arrayUnion($arr2, $argsCount[$i]);
			}while($i < $count);
			return $arr2;
		} 
	}
	
	/**
	 * 检查是否为关联数组
	 */
	public static function isAssocArray(array $arr): bool
	{
		return array_diff_assoc(array_keys($arr), range(0, sizeof($arr))) ? true : false;
	}
}
